<!--
* description:
* author: xiaochengzuan
* createdDate: 2021-1-25
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="popupsVisible"
      width="70%"
      @close="closeEdit"
      @open="open"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <one-table-template
        ref="multipleTable"
        :key="oneTableKey"
        :dynamic-buttons="tableButtons"
        :dynamic-components="tableComponents"
        :dynamic-api-config="apiConfig"
        :dynamic-table-cols="tableCols"
        :dynamic-form-fields="formField"
        :dynamic-is-show-select="true"
        :dynamic-is-init-table="false"
        :callback-obj="callbackObj"
        :dynamic-api-style="'restful'"
        :dynamic-table-defult-height="350"
        :is-show-pagination="false"
      >
        <template #lackQty="scope">
          <el-input
            v-model="scope.row['lackQty']"
            placeholder="申请数量"
            @input="lackQtyChange($event, scope)"
          />
        </template>

      </one-table-template>
    </el-dialog>
<!--    <detail-->
<!--      :dynamic-edit-row-data="editRowData"-->
<!--      :popups-visible-time="popupsVisibleTime"-->
<!--      :num-list="numList"-->
<!--      :dynamic-api-style="'restful'"-->
<!--      @list="upSon($event)"-->
<!--      @close="close"-->
<!--    />-->
    <part-select
      :is-view-part.sync="isViewPart"
      :row-data="rowData"
      price-field="userPrice"
      :close-disabled="true"
      :chosen-list.sync="chosenList"
      :custom="customObj"
      :cur-select-list.sync="curSelectList"
      @selectiondataPart="selectiondata2"
    />
  </section>
</template>
<script>
import { formMixins } from '@/components/mixins/formMixins'
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { orgApis } from '@/api/paSparePartsManagement'
import OneTableTemplate from '@/components/templates/oneTable'
import partSelect from '@/views/pa/purchasingManagement/partOrderBranchMake/partSelectNew.vue'
export default {
  components: {
    OneTableTemplate,
    dialogHeader: () => import('@/components/dialogHeader'),
    partSelect,
    // mixButton: () => import('@/components/basicComponent/mixButton'),
    // Detail: () =>
    //   import('../../InternalUseHeadquarters/internalRequisition/edit')
  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins, formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function() {
        return {}
      }
    },
    codeOpenList: { type: Number, default: 1 }
  },

  data() {
    const viewPageCode = 'bigAreaInfo-edit'
    return {
      isViewPart: false,
      rowData: {},
      chosenList: [],
      curSelectList: [],
      customObj: {
        api: {
          APIUrl: '/mp/e3sh/spareparts/missingDocumentRegistrationService/partsSelect.do',
          ServiceCode: 'partsSelect'
        },
        tableComponents: [
          {
            compKey: 'compKey1',
            labelName: '备件编码：',
            codeField: 'partNo',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey2',
            labelName: '备件名称：',
            codeField: 'partName',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey4',
            labelName: '维修类别：',
            codeField: 'partRepairType',
            component: () => import('@/components/org/commonSelect'),
            type: 'dropdownList',
            customObj: {
              api: orgApis.dropDownKey
            },
            isMust: true
          },
          {
            compKey: 'compKey5',
            labelName: '销售开关：',
            codeField: 'isSale',
            component: () => import('@/components/org/LookupValue'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '1', statusText: '启用' },
              { statusId: '0', statusText: '停用' }
            ],
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey6',
            labelName: '订货开关：',
            codeField: 'isOrder',
            component: () => import('@/components/org/LookupValue'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '1', statusText: '启用' },
              { statusId: '0', statusText: '停用' }
            ],
            type: 'dropdownList',
            isMust: true
          },
          {
            compKey: 'compKey7',
            labelName: '供应商：',
            codeField: 'supplierCode',
            component: () =>
              import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey8',
            labelName: '适用车型：',
            codeField: 'carConfigIdList',
            component: () =>
              import('@/components/org/commonInput'),
            type: 'dropdownList',
            isMust: true
          }
        ],
        tableCols: [
          {
            prop: 'partNo',
            label: '备件编码',
            align: 'center',
            width: 110
          },
          {
            prop: 'partName',
            label: '备件名称',
            align: 'center',
            width: 135
          },
          {
            prop: 'partStatusName1',
            label: '维修类型',
            align: 'center'
          },
          {
            prop: 'carConfigIdList',
            label: '适用车型',
            align: 'center',
            width: 120
          },
          {
            prop: 'userPrice',
            label: '参考价格',
            align: 'center'
          },
          // {
          //   prop: 'minSalesPage',
          //   label: '最小销售包装',
          //   align: 'center'
          // },
          // {
          //   prop: 'isRetrospect',
          //   label: '追溯备件',
          //   align: 'center'
          // },
          // {
          //   prop: 'supplierCode',
          //   label: '供应商编码',
          //   align: 'center'
          // },
          // {
          //   prop: 'supplierShortName',
          //   label: '供应商名称',
          //   align: 'center'
          // },
          // {
          //   prop: 'remark',
          //   label: '备注',
          //   align: 'center'
          // }
        ],
        formField: {
          partNo: '',
          partName: '',
          partRepairType: '',
          isSale: '',
          isOrder: '',
          supplierCode: '',
          carConfigIdList: '',
          warehouseId: ''
        }
      },
      numList: 1,
      apiConfig: orgApis.shortageQueryInfo,
      editRowData: {},
      deteleArray: [],
      popupsVisibleTime: false,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          icon: '',
          clickEvent: () => this.opendEdit(),
          text: '备件选择',
          position: 'left'
        },

        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          icon: '',
          clickEvent: () => this.deteleList(),
          text: '备件删除',
          position: 'left'
        },
        {
          compKey: 'btnKey7',
          type: 'text',
          size: 'small',
          name: '',
          position: 'upload',
          click: event => {
            this.templateDownload()
          }
        },
        {
          compKey: 'btnKey5',
          type: '',
          size: 'small',
          name: 'import',
          clickEvent: () => this.handFileListChange(),
          text: '批量导入',
          position: 'upload'
        },

        {
          compKey: 'btnKey6',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.editSave(1),
          text: '保存',
          position: 'right'
        },
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.editSave(2),
          text: '提交' /* 保存*/,
          position: 'right'
        },

        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        }
      ],

      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: 'compKey1',
          labelName: '缺件单号：',
          codeField: 'lackPartsCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isRequire: false,
          isMust: true,
          disabled: true
        },

        {
          compKey: 'compKey2',
          labelName: '关联类型: ',
          codeField: 'associationType',
          component: () => import('@/components/org/commonSelect'),
          customObj: {
            api: orgApis.queryDropDownG,
            defOptionFields: ['lackPartsSource', 'lackPartsSourceName']
          },
          type: 'dropdownList',
          isRequire: true,
          isMust: true
        },
        {
          compKey: 'compKey3',
          labelName: '关联单号：',
          codeField: 'associationNo',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true
        },

        {
          compKey: 'compKey4',
          labelName: '缺件来源: ',
          codeField: 'lackPartsSource',
          component: () => import('@/components/org/commonSelect'),
          type: 'dropdownList',
          customObj: {
            api: orgApis.shortageQueryDropDown,
            defOptionFields: ['lackPartsSource', 'lackPartsSourceName']
          },
          isMul: false,
          isRequire: true,
          isMust: true
        },
        {
          compKey: 'compKey5',
          labelName: '登记人员：',
          codeField: 'registerPerson',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true
        },
        {
          compKey: 'compKey6',
          labelName: '紧急度: ',
          codeField: 'urgency',
          component: () => import('@/components/org/LookupValue'),
          oFields: 'statusId,statusText',
          options: [
            { statusId: '0', statusText: '一般' },
            { statusId: '1', statusText: '紧急' }
          ],
          type: 'dropdownList',
          isMul: false,
          isMust: true,
          isRequire: true
        },
        {
          compKey: 'compKey7',
          labelName: '车牌号：',
          codeField: 'carLicense',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          validrule: {
            iscPattern: true
          }
        },
        {
          compKey: 'compKey8',
          labelName: 'VIN：',
          codeField: 'vin',
          isRequire: true,
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          // validrule: {
          //   isformat: /^[0-9]{0,17}$/,
          //   resectMessage: {
          //     isformat: '请输入正确的Vin!'
          //   }
          // }
        },
        {
          compKey: 'compKey9',
          labelName: '客户名称：',
          codeField: 'customerName',
          isRequire: true,
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true
        },
        {
          compKey: 'compKey10',
          labelName: '联系电话：',
          codeField: 'customerPhone',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          validrule: {
            isformat: /^[1][3,4,5,7,8][0-9]{9}$/
          }
        },
        {
          compKey: 'compKey11',
          labelName: '备注：',
          codeField: 'remark',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: false,
          span: 12
        }
        //  {
        //   compKey: 'compKey12',
        //   labelName: '1111：',
        //   codeField: 'lackPartsId',
        //   component: () => import('@/components/org/commonInput'),
        //   type: 'inputText',
        //   hidden: true,
        // }
      ],

      tableCols: [
        {
          prop: 'releaseId',
          label: '主键ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlId',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'partNo',
          label: '备件编号',
          hidden: false
          //   alwaysHidden: true
        },
        {
          prop: 'partName',
          label: '备件名称'
        },
        {
          prop: 'partStatusName1',
          label: '备件类别'
        },
        {
          prop: 'carConfigIdList',
          label: '适用车型'
        },
        //       {
        //   prop: 'bigAreaCode',
        //   label: '实际可用'
        // },
        {
          prop: 'snp',
          label: '最小销售包装'
        },
        {
          prop: 'pointPriceTax',
          label: '参考价格'
        },
        {
          prop: 'userPrice',
          label: '销售价格'
        },
        {
          prop: 'lackQty',
          label: '缺件数量+',
          // isComponent: true,
          isSlot: true
          // comps: [
          //   {
          //     compKey: "lackQty",
          //     codeField: "lackQty",
          //     component: () => import("@/components/org/commonInput")
          //   }
          // ]
        },

        {
          prop: 'expectedDeliveryDate',
          label: '希望到货日期',
          isComponent: true,
          comps: [
            {
              compKey: 'expectedDeliveryDate',
              codeField: 'expectedDeliveryDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateOptionsType:'3'
            }
          ]
        }
      ],

      // 标题
      textMap: {
        edit: '缺件信息维护',
        add: '缺件信息维护'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(
        this,
        {
          lackPartsCode: '',
          associationType: '',
          associationNo: '',
          lackPartsSource: '',
          carLicense: '',
          vin: '',
          customerName: '',
          customerPhone: '',
          registerPerson: '',
          urgency: '',
          remark: '',
          lackPartsId: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      callbackObj: {
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelect: (selection, row) => {
          this.deteleArray = selection
        },
        onCheckSelectAll: selection => {
          this.deteleArray = selection
        }
      }
    }
  },

  methods: {
    // 备件选择
    selectiondata2(selectiondata) {
      this.$refs['multipleTable'].list.push(...selectiondata)
    },
    lackQtyChange(val, scope) {
      const reg = /c|(^[0-9]+$)/
      if (!reg.test(val)) {
        this.$message('请输入正确的数量！')
        scope.row['lackQty'] = ''
      }
    },

    opendEdit() {
      this.rowData = {}
      this.chosenList = this.$refs['multipleTable'].list.map(row => row['partId'])
      const lis = this.$utils.deepCopy(this.$refs['multipleTable'].list)
      lis.forEach(o => o['cur'] = true)
      this.curSelectList = lis
      this.isViewPart = true
    },
    open() {
      if (this.codeOpenList === 2) {
        this.$refs['multipleTable'].queryTable(1)
      }
    },
    close(type) {
      this.popupsVisibleTime = type
    },
    upSon(base) {
      this.$refs['multipleTable'].list = base.concat(
        this.$refs['multipleTable'].list
      )
    },
    closeEdit() {
      this.$emit('update:popupsVisible', false)
    },
    deteleList() {
      for (const i of this.deteleArray) {
        this.$refs['multipleTable'].list = this.$refs[
          'multipleTable'
        ].list.filter(item => item !== i)
      }
    },
    // 暂存/保存(接口一致，只是传参不同)
    editSave(sum) {
      // 校验主单数据
      this.$utils.validataMoth(this, 'validpage')
      if (!this.valid) {
        this.$message({
          message: '请填写完必填项!',
          type: 'warning',
          duration: 2000
        })
        return
      }
      if (!this.$refs['multipleTable'].list.length) {
        this.$message({
          message: '请选择备件种类!',
          type: 'warning',
          duration: 2000
        })
        return
      }
      let isValid = true
      this.$refs['multipleTable'].list.every(row => {
        if (!row['lackQty'] || row['lackQty'] == '0') {
          isValid = false
          return false
        }
        return true
      })
      if (!isValid) return this.$message('网格中[ 缺件数量+ ]为必填！')
      if (
        this.formField.customerPhone &&
        this.formField.customerPhone.length !== 11
      ) {
        this.$message({
          message: '手机号格式不正确',
          type: 'warn',
          duration: 1000
        })
        return
      }
      console.log(sum, 'sum')
      if (sum === 2) {
        this.formField.lackPartsId = this.dynamicEditRowData.lackPartsId
      } else if (sum === 1) {
        this.formField.lackPartsId = ''
      }
      const infoList = this.formField
      infoList.tPaBuLackPartsDS = this.$refs['multipleTable'].list
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: orgApis.shortageAuditMoreListSave,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: infoList
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: this.$t('sys.tips.esTip5') /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.popupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message: '保存失败:' + response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('缺件登记模板.xlsx')
      this.$requestAPI({
        apiUrl: orgApis.partsDwnloadTemplate.APIUrl,
        variables: { dataType: 'excel' }
      })
        .then(res => {
          this.$utils.downloadFile(res, fileName)
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 批量导入
    handFileListChange(file, fileList) {
      this.handleChange(file)
    },
    handleChange(param) {
      const that = this
      const url =
        '/mp/e3sh/spareparts/missingDocumentRegistrationService/importExcel.do'
      that
        .$requestUpload(url, param)
        .then(response => {
          response.rows.forEach(element => {
            this.$refs.multipleTable.list.push(element)
          })
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch(err => {
          this.$message({
            message: response.msg,
            type: 'warning'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.promptSpan {
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>
